Lesson 7: Printer Friendly

Create a Storefront Web Application

Printing This Lesson

Select what you’d like to include when you print, and then click the Print Lesson button:

Saving This Lesson

For instructions on saving this lesson (shown below), please select the browser you're using.

chrome icon
Chrome
Firefox icon
Firefox
Internet Explorer 10 icon
IE
Safari icon
Safari

Chapter 1

Introduction

Hi there! In today's lesson, we'll turn our attention to the storefront Web pages. These pages are important, as they're what your customers see and use to purchase your products. You want the storefront Web pages to flow smoothly and provide a positive customer shopping experience.

In the first part of this lesson, you'll see just what a storefront Web page is and what you need to produce one. Many commercial online shops spend lots of money trying to figure out which techniques work and which ones don't. You get to benefit from all their work.

Next, you'll discover the components of the Food Store storefront and learn about each of the PHP files required to implement the features that are important for your customers. You'll build the Web page template that you'll use to implement each of the features in your storefront.

Finally, we'll start to talk about an element that's crucial to your customer's shopping experience—the shopping cart. You'll see what you need to do to create a shopping cart so your customer can easily select items to purchase and have them available at checkout.

Let's move on and get started.

Chapter 2

The Storefront

The main Web page in a store application is called the storefront. The storefront Web page must do several jobs for your customer:

  • Provide basic information about the store.
  • Provide an easy method for customers to navigate through the store.
  • Provide information on what products are available for purchase.
  • Provide a way for customers to select products for purchase.
  • Provide an easy method for checking out.
  • Provide contact information in case a customer has problems with the store.
  • Provide specialized information, such as sales and news events.

There are lots of ways to present this information in the storefront. I'm sure you've seen (and probably even used) many of the thousands of online shopping Web sites and have seen different techniques used to implement these features.

The Food Store uses a common Web page approach to present the storefront. By using a common Web page, the general layout of each page in the store is the same. The only thing that changes is the main content in the page. This allows you to guide the customer through different parts of the store using a common interface.

The storefront uses the same template we used to create the back-end application. This provides for a Web page with five sections:

  • A header section for displaying standard store information.
  • A footer section for displaying contact information.
  • A navigation section for allowing the customer to easily jump to any location in the store.
  • A shopping cart section to provide instant information on items the customer selects for purchase.
  • A main section where customers can browse and select items from a catalog of products, then checkout when they're done shopping.

The Food Store storefront

The Food Store storefront

Before we get too deep in the application code required to run the main section of the storefront, let's take a quick look at the template code we'll use to create the common Web page interface.

Creating the Storefront

The basic storefront template copies from the admin.php code we used for the back-end application. Follow these steps to create the storefront template:

  1. Create a file called index.php in the store folder.
  2. Enter the following code into the new file:
  3. Print code

    <?php
    session_start();
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <link rel="stylesheet" type="text/css" href="mystyle.css" />
    <title>The Food Store</title>
    </head>

    <?php include("mylibrary/login.php"); include("mylibrary/showproducts.php");

    login(); ?>

    <body> <table width="100%" border="0"> <tr> <td id="header" height="90" colspan="3"> <?php include("header.inc.php"); ?></td> </tr> <tr> <td id="nav" width="20%" valign="top"> <?php include("nav.inc.php"); ?></td> <td id="main" width="50%" valign="top"> <?php if (!isset($_REQUEST['content'])) include("main.inc.php"); else { $content = $_REQUEST['content']; $nextpage = $content . ".inc.php"; include($nextpage); } ?></td> <td id="status" width="30%" valign="top"> <?php include("cart.inc.php"); ?></td> </tr> <tr> <td id="footer" colspan="3"> <div align="center"> <?php include("footer.inc.php"); ?> </div></td> </tr> </table> </body> </html>

  4. Save the file and exit the editor.
  5. The index.php file uses the same header.inc.php, footer.inc.php, and mystyle.css files that the back-end application uses. Copy each of these files from the admin folder to the store folder.

The storefront index.php file starts with a small piece of PHP code:

<?php
session_start();
?>

This code is crucial to using session cookies, which we'll discuss later in this lesson.

You now have the core template complete for your storefront. Now, you can move on to creating the navigation section.

Creating the Navigation Section

Your navigation section should provide simple links for the customer to find his or her way around the store Web pages. One common technique for storefronts is to provide links to separate categories within the catalog and indicate how many items are available in each category. You can do this easily with PHP code. Let's build the nav.inc.php file, which provides this feature:

  1. Create the file nav.inc.php in the store folder.
  2. Enter the following code into the file:
  3. Print code

    <table width="100%" cellpadding="2">
      <tr>
        <td><h3>Welcome to the store!</h3></td>
      </tr>
      <tr>
        <td><a href="index.php"><strong>Home</strong></a></td>
      </tr>
      <tr>
        <td><hr size="1" noshade="noshade" /></td>
      </tr>
      <tr>
        <td>
           <label><h3>Browse Products:<br><br></h3> </label>
           <?php
             $query="SELECT catid,name from categories";
             $result=mysql_query($query);
             while($row=mysql_fetch_array($result,MYSQL_ASSOC))
             {
                 $catid = $row['catid'];
                 $name = $row['name'];
                 $query2="SELECT count(prodid) FROM products WHERE catid = $catid";
                 $result2 = mysql_query($query2);
                 $row=mysql_fetch_array($result2);
                 $total = $row[0];
                 echo "<a href=\"index.php?content=buyproducts&cat=$catid\">$name</a> ($total)<br>\n";
             }
           ?>
       </td>
      </tr>
      <tr>
        <td><hr size="1" noshade="noshade" /></td>
      </tr>
      <tr>
        <td>
    <form action="index.php" method="get">
        <label><font color="#663300" size="-1">search for product:</font> </label>
          <input name="searchFor" type="text" size="14" />
          <input name="goButton" type="submit" value="find" />
          <input name="content" type="hidden" value="search" />
      </form>  </td>
      </tr>
      <tr>
        <td><hr size="1" noshade="noshade" /></td>
      </tr>
      <tr>
        <td><a href="index.php?content=reviewcart"><strong>Review shopping cart</strong></a></td>
      </tr>
      <tr>
        <td><hr size="1" noshade="noshade" /></td>
      </tr>
      <tr>
        <td bgcolor=#FFFF99><a href="index.php?content=checkout"><strong>Check out</strong></a></td>
      </tr>
      <tr>
        <td><hr size="1" noshade="noshade" /></td>
      </tr>
      <tr>
        <td> </td>
      </tr>
    </table>

  4. Save the file and exit the editor.

The nav.inc.php code provides several features in the navigation section:

  • A Home link to return to the storefront Web page.
  • A Browse Products area with links to go to a specific location in the catalog.
  • A Search textbox and button to allow searching products.
  • A Review Shopping Cart link, allowing the customer to view and modify the current shopping cart contents.
  • A Check Out link that allows the customer to purchase the items contained in the shopping cart.

The PHP code that creates the Browse Products area performs one SQL query to retrieve all of the categories in the categories table, and then it performs a second query to tally the number of products in each category. This is a common practice in storefront applications.

That's the core of the storefront template code. In the next chapter, you'll work on getting the PHP code for the storefront main section working.

Chapter 3

The Storefront Main Section

The main section in your storefront should provide information that you want the customer to see immediately. You can include a greeting, store notices, and special event items, such as sale items or news flashes.

The Food Store storefront main section displays a simple greeting, followed by the products that are currently on sale. This allows customers to select sale items easily without having to hunt for them in the normal catalog listings.

To do this, you'll need to query the products database to find the items that the manager marked as being on sale. Remember, the onsale data field in the products table indicates if a product is on sale. It's a Boolean value, so you'll need to be careful when querying for this value. There's a simple trick to create the query for this:

SELECT * FROM products WHERE onsale = TRUE

The Boolean data type has two possible values—0 or 1. When you perform your query, you can use the numerical values of zero or one, or you can use alias values of TRUE (for one) or FALSE (for zero). In the application, a TRUE value indicates the product is on sale.

When you display the list of products that are on sale, it's a good idea to provide as much information as possible (including the stored image), and a link, so the customer can purchase the product directly from the main Web page.

Let's build the main.inc.php file, which displays the content for the main section:

  1. Create the file main.inc.php in the store folder.
  2. Open the file in an editor, and enter the following code:
  3. Print code

    <h2>Welcome to our store!</h2>
    <br>
    <br>
    <p>Please feel free to browse our great selection of products. Select the category
    from the drop-down menu in the navigation bar. Add items to your cart, then check out.
    <p>

    <h2>Items on sale today:</h2>

    <?php $query = "SELECT * from products where onsale = TRUE"; $result = mysql_query($query);

    echo "<table width=\"100%\" border=\"0\">\n"; while($row=mysql_fetch_array($result, MYSQL_ASSOC)) { $prodid = $row['prodid']; $description = $row['description']; $price = $row['price']; $quantity = $row['quantity']; echo "<tr><td>\n"; echo "<img src=\"showimage.php?id=$prodid\" width=\"80\" height=\"60\">"; echo "</td><td>\n"; if ($quantity == 0) echo "<font size=\"3\">$description</font>\n"; else { echo "<a href=\"index.php?&content=updatecart&id=$prodid\">"; echo "<font size=\"3\"><b><u>$description</u></b></font>\n"; } echo "</td><td>\n"; printf("$%.2f\n", $price); echo "</td><td>\n"; if ($quantity == 0) echo "<font color=\"red\">Sorry, this item out of stock</font>\n"; else if ($quantity < 5) echo "Hurry, only $quantity left in stock!\n"; else echo " \n"; echo "</td></tr>\n"; } echo "</table>\n"; ?>

  4. Save the file and exit the editor.
  5. Notice that this code uses the showimage.php file you created earlier for the back-end application, so you could display an image on a Web page. Copy the showimage.php file from the admin folder to the store folder.

The main.inc.php code displays a short message about the store to the customer. It then performs a simple SQL query, looking for all the products marked as on sale. It iterates through the returned data records, displaying each product on a separate line.

You'll note that the code checks the quantity in stock for each product. If a product has more than five in stock, no special messages are displayed, and the product description is displayed as a link to the updatecart content (which we'll discuss later). If a product has less than five in stock, the code displays a special message indicating how many are left. Finally, if a product is out of stock, the code displays the product description as regular text without the link (since there aren't any to purchase).

You may have noticed that I snuck in a different way of displaying the price data field:

printf("$%.2f\n", $price);

If you've ever used the C programming language, you know exactly what the printf() function does. If you're not a C programming guru, let me explain a little.

The printf() function provides for extremely fine control over displaying data. It uses special formatting codes that allow you to define what type of data to display and how to display it. The format of the printf() function is:

printf("format", variable list)

The format parameter defines what you want the printf() function to print. The format parameter consists of normal text, along with special codes for printing variables. There are lots of special codes that the printf() function supports, but the ones most often used are:

The printf() function codes
Code Description
%c Displays a single character value.
%d Displays an integer value.
%f Displays a floating point value.
%s Displays a string value.

The format string contains special codes for each variable you want to display. You must then specify the variables in the correct order in the variables list. This goes something like this:

printf("You purchased %d of %s", $quantity, $description);

The printf() function matches the $quantity variable value with the %d code to display the integer value, and the $description variable value with the %s code to display the string value.

Now here's where it gets interesting. You defined the price data field in the products table as a decimal(6,2) data type. When you extract this value, using the mysql_fetch_array() function, it becomes a floating point value in PHP. If you use the echo statement to display this value, it'll drop the decimal places if they're zero. This would look somewhat clunky for customers. They're used to seeing dollar values look like $1.50 and not $1.5.

The printf() function allows you to not only specify that a data element is a floating point value with the %f code, it also allows you to specify the number of decimal places to always display. You do that by placing the value between the percent sign and the f code:

printf("The cost of the item is $%.2f\n", $price);

This format will always display a two-decimal place value, even if one or both of the trailing values is zero.

This demonstrates the power you have while generating Web sites with PHP code. You can display your data in any format you desire by creating the HTML code within your PHP printf() statements.

Let's continue on to Chapter 4 and talk about the last section on the storefront home page, the shopping cart.

Chapter 4

The Shopping Cart Section

Your shopping cart section of the storefront displays the shopping cart information for the customer. This provides a real-time update for all of the items the customer has selected for purchase. The customer knows at any time what items are in the shopping cart just by glancing at the shopping cart section, which appears on all Web pages in the storefront.

The key to the shopping cart is the PHP session cookie. Each time a customer accesses your Web site, he or she creates a session. The Apache server assigns each session a unique session ID that it tracks on the server. PHP allows you to store data within the session, called a session cookie. When you use the session_start() function at the beginning of your Web session, PHP allows you to access data stored in the session cookies. The session cookie stores multiple data values as an array variable.

Session cookies only last for the duration of the browser session. By default, when a customer closes the browser window, the session cookie disappears.

Storing Arrays in Session Cookies

So far, you've seen that the session cookie is an associative array where you can store multiple values by defining a key and a value:

$_SESSION['user'] = $userid;

You could use this technique to store the products the customer selects for purchase, but things would get tricky. You could use the product description as the associative key, but that could get messy, depending on the products sold in the store. A better solution is to use the product ID for the product selected as the key and store the quantity purchased as the value:

$_SESSION[1] = 10;
$_SESSION[6] = 5;

This would work, but it would make life more difficult if you needed to store additional information, such as the customer name and address. If you added additional keys for customer information, you wouldn't be able to tell which cookies were products and which were customer information.

The simple solution to this challenge is to use multidimensional arrays. A multidimensional array is nothing more than an array variable where each element in the array contains an array variable. If it sounds confusing, it really isn't.

The multidimensional array allows you to create a session cookie value that contains an array of values. This way, you can create a single session cookie, called a cart. It contains an array consisting of the selected product IDs as keys and the quantities as values. Using this method, you can also create an additional session cookie, called user, to track the user ID of the customer session, and you can easily tell which session cookie contains the shopping cart data.

To create an array within a session cookie, just use the array() function and start assigning keys and values. It'll look something like this:

$_SESSION['cart'] = array();
$_SESSION['cart'][1] = 10;
$_SESSION['cart'][6] = 5;

Notice that the multidimensional array adds the second array keys onto the session cookie array key (cart).

You'll use a couple of functions when working with the arrays. When you want to count how many items are in the shopping cart, use the following code:

$items = count($_SESSION['cart']);

This returns the number of keys in the multidimensional array within the cart array. Just like a regular array, if you want to iterate through all of the product keys, you can use the foreach() function:

foreach( $_SESSION['cart'] as $prodid => $quantity)
{
   echo "You purchased $quantity  of product ID: $prodid
}

To add more of a product that's already in the cart, you increase the quantity value:

$_SESSION['cart'][1] = $_SESSION['cart'][1] + 3;

The same obviously applies if you want to remove some of the product quantity from the shopping cart. If you want to remove a product completely from the shopping cart, you can use the unset() function:

unset($_SESSION['cart'][1]);

Armed with this new knowledge of session cookies, you can create the cart.inc.php program. This program will create the shopping cart variable if it doesn't exist and then display the current products stored in the shopping cart. Just follow these steps:

  1. Create the file cart.inc.php in the store folder.
  2. Open the file and enter the following code:
  3. Print code

    <?php
       echo "<h2>Your shopping cart:</h2>\n";

    if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = array(); echo "is empty\n"; } else { $items = count($_SESSION['cart']); if ($items == 0) { echo "is empty\n"; } else { $total = 0; echo "<table width=\"100%\" cellpadding=\"1\" border=\"1\">\n"; echo "<tr><td>Product</td><td>Quantity</td><td>Total</td></tr>\n"; foreach($_SESSION['cart'] as $prodid => $quantity) { $query = "SELECT description, price FROM products WHERE prodid = $prodid"; $result = mysql_query($query); $row = mysql_fetch_array($result, MYSQL_ASSOC); $description = $row['description']; $price = $row['price'];

    $subtotal = $price * $quantity; $total += $subtotal;

    printf("<tr><td>%s</td><td>%s</td><td>$%.2lf</td></tr>\n", $description, $quantity, $subtotal); } printf("<tr><td colspan=\"2\">Total</td><td>$%.2lf</td></tr>\n", $total); echo "</table>\n";

    } } ?>

  4. Save the file and exit the editor.

The first section uses the standard isset() function to determine if the shopping cart already exists. If it doesn't (the first time the customer connects to the Web page), it creates it in the session cookie. If the session cookie exists, the code uses the count() function to see if there are any products in the shopping cart. If so, it's just a matter of using the foreach() function to iterate through each value and displaying its information.

The cart.inc.php code makes use of the printf() function to ensure that the price values stay in the proper format.

We covered a lot of ground in the project today. Let's go to Chapter 5 and review all you did.

Chapter 5

Summary

Today you learned to design and create a storefront Web page. The storefront page must present lots of information about the store and products to attract customers and get them to stay.

The Food Store storefront uses the principle of dividing the Web page into sections. The header, footer, navigation, and shopping cart sections all provide simple interfaces for providing basic information to the customer.

The opening storefront main section provides a simple greeting and displays the products that are currently on sale. The product listing allows a customer to select a product immediately for purchase. To display the on-sale products, you query for a Boolean data type in the SELECT statement. The TRUE and FALSE alias names provide a handy way to remember the Boolean states of the data.

In the main section code, you also saw how the PHP printf() function provides a way for you to use more precise control in displaying data, especially floating point values that represent money amounts.

Finally, you discovered the basics of the shopping cart and how to initialize the cart and display the products stored in it.

In the next lesson, we'll dive deeper into the shopping cart world, learning how to add new items to it, modify items that are already in it, and remove items from it.

Supplementary Material

http://us.php.net/manual/en/function.sprintf.php
http://www.morebusiness.com/getting_started/website/d908484170.brc

FAQs

Q: Can I use session cookies if the client's browser doesn't accept cookies?

A: Possibly. The PHP configuration file uses the session.use_only_cookies parameter. When this value is set to 1, the client's browser must accept cookies, or the session cookie will fail. If the value is set to 0 (when the client's browser rejects cookies), PHP automatically incorporates the session cookie into the URL. Be careful with this setting, though—a third party could easily hijack it.

Assignment


For today's assignment, you should experiment with the products in the store and see how that affects the storefront. First, use the back-end application you've already created to edit a couple of products and place them on sale. Remember how to do that?

Next, go to your new storefront Web page using the URL: http://localhost/store/. You should see the storefront, including the two products you placed on sale.

After that, go back into the back-end application and change the quantity value of the products you placed on sale. For one, make its quantity equal to four, and for another, set it to zero. Go back to the storefront and see if the sale information has changed. Are you starting to see the power of using dynamic PHP coding in your storefront? You can control exactly what your customers see and when they see it.